#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
配置加载工具
"""

import os
import yaml
import logging


def load_config(config_path):
    """
    加载YAML配置文件
    
    Args:
        config_path (str): 配置文件路径
    
    Returns:
        dict: 配置字典
    
    Raises:
        FileNotFoundError: 配置文件不存在时抛出
        yaml.YAMLError: YAML解析错误时抛出
    """
    logger = logging.getLogger()
    
    try:
        # 确保文件存在
        if not os.path.exists(config_path):
            raise FileNotFoundError(f"配置文件不存在: {config_path}")
        
        # 读取YAML配置
        logger.info(f"加载配置文件: {config_path}")
        with open(config_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        
        # 返回加载的配置
        return config
    except FileNotFoundError as e:
        logger.error(f"配置文件错误: {str(e)}")
        raise
    except yaml.YAMLError as e:
        logger.error(f"YAML解析错误: {str(e)}")
        raise
    except Exception as e:
        logger.error(f"加载配置时发生未知错误: {str(e)}")
        raise


def save_config(config, file_path):
    """
    保存配置到YAML文件
    
    Args:
        config (dict): 配置字典
        file_path (str): 保存路径
    """
    logger = logging.getLogger()
    
    try:
        # 确保目录存在
        os.makedirs(os.path.dirname(file_path), exist_ok=True)
        
        # 保存YAML配置
        logger.info(f"保存配置到: {file_path}")
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(config, f, default_flow_style=False, allow_unicode=True)
    except Exception as e:
        logger.error(f"保存配置时发生错误: {str(e)}")
        raise


def merge_configs(config1, config2):
    """
    合并两个配置字典，config2的值会覆盖config1的相同键
    
    Args:
        config1 (dict): 基础配置
        config2 (dict): 覆盖配置
    
    Returns:
        dict: 合并后的配置
    """
    if config2 is None:
        return config1
    
    result = config1.copy()
    
    # 递归合并字典
    for key, value in config2.items():
        if (
            key in result and 
            isinstance(result[key], dict) and 
            isinstance(value, dict)
        ):
            result[key] = merge_configs(result[key], value)
        else:
            result[key] = value
    
    return result 